
import urllib
import socket
from Debug		import *

#####################################################################################################################################
# AlbumResult class
class WebService:
	SERVER_ARTIST='http://musicbrainz.org/ws/1/artist/'
	SERVER_RELEASE='http://musicbrainz.org/ws/1/release/'
	SERVER_TRACK='http://musicbrainz.org/ws/1/track/'
	LASTFM_API_KEY='38b884487c776fddc61e2d13f71c0c86'
	LASTFM_SERVER='http://ws.audioscrobbler.com/2.0/'

	@staticmethod
	def __get_file__(server, id, params):
		params_encode = urllib.urlencode(params)
		DEBUG(server+id+'?'+params_encode)
#		socket.setdefaulttimeout(0.1)
		opener = urllib.FancyURLopener()
		print 'asd'
		file = opener.open(server+id+'?'+params_encode)
		print file
		return file
	
	@staticmethod
	def open(url):
		return urllib.FancyURLopener().open(url)
	
	@staticmethod
	def get_artist(name = None, id = None):
		params = {}
		params['type'] = 'xml'
		if name is not None:
			params['query'] = name
			return WebService.__get_file__(WebService.SERVER_ARTIST,'', params)
		if id is not None:
			 return WebService.__get_file__(WebService.SERVER_ARTIST,str(id).strip(), params)
	
	@staticmethod
	def get_albums(artist):
		params = {}
		params['type'] = 'xml'
		params['inc'] = 'sa-Album release-events'
		return WebService.__get_file__(WebService.SERVER_ARTIST, str(artist.ID),params)
	
	@staticmethod
	def get_tracks( album):
		params = {}
		params['type'] = 'xml'
		params['inc'] = 'tracks'
		return WebService.__get_file__(WebService.SERVER_RELEASE, str(album.ID), params)
	
	@staticmethod
	def get_track(track):
		params = {}
		params['type'] = 'xml'
		params['inc'] = 'releases'
		return WebService.__get_file__(WebService.SERVER_TRACK, str(track.ID), params)

	@staticmethod		
	def get_album_info(artist, album):
		params = {}
		params['method'] = 'album.getinfo'
		params['api_key'] = WebService.LASTFM_API_KEY
		params['artist'] = artist
		params['album'] = album
		return WebService.__get_file__(WebService.LASTFM_SERVER, '', params)
